	/* Copyright (c) 2006-2010 by OpenLayers Contributors (see authors.txt for 
 * full list of contributors). Published under the Clear BSD license.  
 * See http://svn.openlayers.org/trunk/openlayers/license.txt for the
 * full text of the license. */


/**
 * @requires OpenLayers/Layer/Grid.js
 * @requires OpenLayers/Tile/Image.js
 */

/**
 * Class: OpenLayers.Layer.GeoWebCache
 * A variant of the TMS layer, this allows for viewing raw GeoWebCache cached tiles,
 * making this useful for viewing caches, or generating caches and serve them off other
 * machine without changing the file naming scheme.
 * In order to do so, just set the "url" property of the layer instance to the path
 * to the cached tiles, minus the zoom level (e.g. ".../path/epsg_namespace_layer_").
 * Also make sure that "type" is set to either "png" or "jpeg", depending on which
 * kind of tiles are in the cache.
 *
 * 
 * Inherits from:
 *  - <OpenLayers.Layer.Grid>
 */
OpenLayers.Layer.GeoWebCache = OpenLayers.Class(OpenLayers.Layer.Grid, {

    /**
     * APIProperty: isBaseLayer
     * {Boolean}
     */
    isBaseLayer: true,

    /**
     * APIProperty: serverResolutions
     * {Array} A list of all resolutions available on the server.  Only set this 
     *     property if the map resolutions differs from the server.
     */
    serverResolutions: null,

    /**
     * APIProperty: zoomOffset
     * {Number} If your cache has more zoom levels than you want to provide
     *     access to with this layer, supply a zoomOffset.  This zoom offset
     *     is added to the current map zoom level to determine the level
     *     for a requested tile.  For example, if you supply a zoomOffset
     *     of 3, when the map is at the zoom 0, tiles will be requested from
     *     level 3 of your cache.  Default is 0 (assumes cache level and map
     *     zoom are equivalent).  Using <zoomOffset> is an alternative to
     *     setting <serverResolutions> if you only want to expose a subset
     *     of the server resolutions.
     */
    zoomOffset: 0,
    
    /**
     * Constructor: OpenLayers.Layer.TMS
     * 
     * Parameters:
     * name - {String}
     * url - {String}
     * options - {Object} Hashtable of extra options to tag onto the layer
     */
    initialize: function(name, url, options) {
        var newArguments = [];
        newArguments.push(name, url, {}, options);
        OpenLayers.Layer.Grid.prototype.initialize.apply(this, newArguments);
    },

    /**
     * APIMethod:destroy
     */
    destroy: function() {
        // for now, nothing special to do here. 
        OpenLayers.Layer.Grid.prototype.destroy.apply(this, arguments);  
    },

    
    /**
     * APIMethod: clone
     * 
     * Parameters:
     * obj - {Object}
     * 
     * Returns:
     * {<OpenLayers.Layer.TMS>} An exact clone of this <OpenLayers.Layer.TMS>
     */
    clone: function (obj) {
        
        if (obj == null) {
            obj = new OpenLayers.Layer.TMS(this.name,
                                           this.url,
                                           this.getOptions());
        }

        //get all additions from superclasses
        obj = OpenLayers.Layer.Grid.prototype.clone.apply(this, [obj]);

        // copy/set any non-init, non-simple values here

        return obj;
    },    
    
    /**
     * Method: getURL
     * 
     * Parameters:
     * bounds - {<OpenLayers.Bounds>}
     * 
     * Returns:
     * {String} A string with the layer's url and parameters and also the 
     *          passed-in bounds and appropriate tile size specified as 
     *          parameters
     */
    getURL: function (bounds) {
	
        bounds = this.adjustBounds(bounds);
	var res = this.map.getResolution();

        var x = Math.round((bounds.left - this.maxExtent.left) 
            / (res * this.tileSize.w));
        var y = Math.round((this.maxExtent.top - bounds.top) 
            / (res * this.tileSize.h));
        var z = this.serverResolutions != null ?
            OpenLayers.Util.indexOf(this.serverResolutions, res) :
            this.map.getZoom() + this.zoomOffset;
	
	/* Pretty much copied bits of GeoWebCache's FilePathGenerator.java */
	/* This way, the code should be compatile bug-for-bug. BTW: GWC's documentation about cache file naming doesn't match the implementation. */
	
	var half = 2 << (z/2)
	
	/* The y coordinate has to be inverted - origin of coordinates between TMS and GWC differs*/
	y = (1<<z) - y - 1;
	
	var halfx =  Math.floor(x/half);
	var halfy =  Math.floor(y/half);
	
	var padLength = String(half).length;
	
	var path = this.prefix + '_' + this.zeropad(String(z),2) + '/' +
		this.zeropad(String(halfx),padLength) + '_' + this.zeropad(String(halfy),padLength) + '/' +
		this.zeropad(String(x),padLength*2) + '_' + this.zeropad(String(y),padLength*2) + '.' + this.type;
	
        var url = this.url;
        var s = '' + x + y + z;
        if (url instanceof Array)
        {
            url = this.selectUrl(s, url);
        }
		
        return url + path;
    },

    /**
     * Method: zeroPad
     * Auxiliary function. zeroPad pads a string with zeroes, Java-style, just as GWC does. Standard (right) printf zero-padding will result in bugs (i.e. missing tiles)
     * 
     * Parameters:
     * string - {string} String to be padded
     * len - {int} Length of resulting string
     * 
     * Returns:
     * {string} the zero-padded string
     */
	zeropad: function(string, len)
	{
		/* Workaround for stupid and nasty GeoWebCache (int) log10(foo+0.001) bug. */
		if (string == '1000')
			return '01000';
		else if (string == '1001')
			return '01001';
		else if (string == '1002')
			return '01002';
		
		while (string.length < len)
			string = '0' + string;
		
		return string;
	},

    /**
     * Method: addTile
     * addTile creates a tile, initializes it, and adds it to the layer div. 
     * 
     * Parameters:
     * bounds - {<OpenLayers.Bounds>}
     * position - {<OpenLayers.Pixel>}
     * 
     * Returns:
     * {<OpenLayers.Tile.Image>} The added OpenLayers.Tile.Image
     */
    addTile:function(bounds,position) {
        return new OpenLayers.Tile.Image(this, position, bounds, 
                                         null, this.tileSize);
    },

    /** 
     * APIMethod: setMap
     * When the layer is added to a map, then we can fetch our origin 
     *    (if we don't have one.) 
     * 
     * Parameters:
     * map - {<OpenLayers.Map>}
     */
    setMap: function(map) {
        OpenLayers.Layer.Grid.prototype.setMap.apply(this, arguments);
        if (!this.tileOrigin) { 
            this.tileOrigin = new OpenLayers.LonLat(this.map.maxExtent.left,
                                                this.map.maxExtent.bottom);
        }
    },

    CLASS_NAME: "OpenLayers.Layer.GeoWebCache"
});